package com.buaa.student.controller;

import com.buaa.student.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
public class LoginController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/login")
    public String loginPage(){
        return "login";
    }

    @PostMapping("/login/auth")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        HttpServletResponse response){

        boolean flag = loginService.checkLogin(username, password);
        if(flag){
            //登录成功
            String token = UUID.randomUUID().toString();
            redisTemplate.opsForValue().set(token,token,3, TimeUnit.DAYS);
            Cookie cookie = new Cookie("token", token);
            cookie.setPath("/");
            cookie.setMaxAge(3*24*60*60);
            response.addCookie(cookie);

            return "index";
        }

        return "redirect:/login";
    }
}
